﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace huqiang.Collections
{
    public class LockStack<T> where T : struct, IClear
    {
        int point = 0;
        T[] buffer;
        int mlen;
        SpinLock spin = new SpinLock();
        //bool valueType;
        public int BufferLenth { get { return mlen; } }
        public int Count
        {
            get
            {
                return point;
            }
        }
        public LockStack(int len = 256)
        {
            buffer = new T[len];
            mlen = len;
            //valueType = typeof(T).IsValueType;
        }
        public bool Push(T t)
        {
            bool gotLock = false;
            try
            {
                spin.Enter(ref gotLock);
                if (point < mlen)
                {
                    buffer[point] = t;
                    point++;
                    return true;
                }
                return false;
            }
            finally
            {
                if (gotLock)
                    spin.Exit();
            }
        }
        public bool Pop(ref T t)
        {
            if (point <= 0)
                return false;
            bool gotLock = false;
            try
            {
                spin.Enter(ref gotLock);
                point--;
                t = buffer[point];
                buffer[point].Clear();
                return true;
            }
            finally
            {
                if (gotLock)
                    spin.Exit();
            }
        }
    }
}
